<template>
    <div class="app-detail">

        <el-form :model="viewModel" ref="planForm" label-width="98px" :rules="isView?null:rules">
            <el-card class="box-card">
                <div class="container-header">
                    <div class="hign-line"></div>
                    <div class="header-left">
                        {{$t('inventoryManagement.baseInfo')}}1
                    </div>
                </div>
                <el-row :gutter="20" class="mb8">
                      <!-- 事业部 新增 -->
                      <el-col :span="6">
                        <el-form-item :label="$t('inspectionStandards.division')" prop="divisionName">
                            <!-- <el-input v-model="viewModel.divisionName" clearable size="small" @keyup.enter.native="handleQuery" /> -->
                            <division-dialog @changeSamplinglist='changeSamplinglist' v-model="viewModel.divisionName" :divisionId.sync="viewModel.divisionId" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('inventoryManagement.materialName')" prop="materialName">
                            <material-dialog :disabled="isView" v-model="viewModel.materialName" @callback="(row)=>materialDataCallback(row)" buildVersion :params="{inspectionId:id!='0'?id:undefined}"/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('inventoryManagement.materialNo')" prop="materialCode">
                            <el-input v-model="viewModel.materialCode" disabled clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <!-- 厂区 -->
                    <el-col :span="6">
                        <el-form-item :label="$t('inspectionManagement.plantArea')" prop="factoryName">
                            <el-select v-model="viewModel.factoryName" :disabled="isView" multiple :placeholder="$t('public.select_holder',{select_holder: $t('inspectionManagement.plantArea')})" style="width:100%;" filterable clearable @visible-change="factoryVisibleFN" @change="factoryChange" size="small">
                                <el-option v-for="(item, key) in factoryList" :key="key" :label="item.newFactoryName" :value="item.plantName" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20" class="mb8">
                    <el-col :span="6">
                        <el-form-item :label="$t('inventoryManagement.frequency')" prop="planFrequency">
                            <el-select v-model="viewModel.planFrequency" :disabled="isView" :placeholder="$t('public.selectPl')" style="width:100%;" clearable size="small">
                                <el-option key="批" label="批" value="批" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('inventoryManagement.frequencyValue')" prop="frequencyValue">
                            <el-input v-model="viewModel.frequencyValue" :disabled="isView" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('inspectionManagement.version')" prop="version">
                            <el-input v-model="viewModel.version" disabled clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item :label="$t('inspectionManagement.revisionDrawing')" prop="drawingsVersion">
                            <el-input v-model="viewModel.drawingsVersion" :disabled="isView" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <!-- 分类移除 -->
                    <!-- <el-col :span="6">
                        <el-form-item :label="$t('inventoryManagement.classify')" prop="classify">
                            <el-select v-model="viewModel.classify" style="width:100%;" filterable :placeholder="$t('public.selectPl')" :disabled="isView" size="small">
                                <el-option size="mini" v-for="item in dict.type.NYIQC_INSPECTIONPLAN_CLASSIFY" :key="item.value" :label="item.label" :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col> -->
                </el-row>
                <el-row :gutter="20" class="mb8">
                    <!-- 基地 新增 -->
                    <el-col :span="6">
                        <el-form-item :label="$t('basicData.baseName')" prop="baseName">
                            <el-input v-model="viewModel.baseName" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                    <!-- 车间 新增 -->
                    <el-col :span="6">
                        <el-form-item :label="$t('basicData.workshop')" prop="workshop">
                            <el-input v-model="viewModel.workshop" clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>
                  <!-- 项目名称 隐藏 -->
                  <!-- <el-col :span="6">
                    <el-form-item label="项目名称" prop="entryName">
                      <el-input v-model="viewModel.entryName" clearable size="small" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                  </el-col> -->
                  <!-- 文件编号 新增 -->
                  <el-col :span="6">
                    <el-form-item :label="$t('task.fileNo')" prop="documentNo">
                      <el-input v-model="viewModel.documentNo" clearable size="small" @keyup.enter.native="handleQuery" />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="20" class="mb8">
                    <el-col :span="24">
                        <el-form-item :label="$t('inventoryManagement.description')" prop="description" style="width:100%">
                            <el-input :disabled="isView" type="textarea" :autosize="{ minRows: 3, maxRows: 4}" v-model="viewModel.description" maxlength="1000">
                            </el-input>
                        </el-form-item>
                    </el-col>

                </el-row>

            </el-card>
            <inspection-item-info-virtual ref="inspectSubmit" :isAdd="isAdd" :itemData="inpectItemData" @callback="submitCallback" :loadings="loading" :samplinglist="currentSamplinglist" />
            <el-card class="box-card">
                <el-row>
                    <el-col :span="24">
                        <el-form-item :label="$t('inspectionManagement.uploadDrawing')" prop="uploadAttachments" style="width:100%">
                            <file-upload :disabled="isView" :limit="1" bizType="UPLOAD_FILE" :otherList="picFile" :bizId="id" v-model="viewModel.uploadAttachments" @change="(fileList)=>picChange(fileList)"></file-upload>
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item :label="$t('basicData.checkWIFile')" prop="checkFile" style="width:100%">
                            <file-upload :disabled="isView" :limit="1" bizType="UPLOAD_FILE_CHECK" :otherList="checkFile" :bizId="id" v-model="viewModel.checkFile" @change="(fileList)=>checkChange(fileList)"></file-upload>
                        </el-form-item>
                    </el-col>

                    <el-col :span="24">
                        <el-form-item :label="$t('inspectionManagement.uploadAttachments')" prop="uploadDrawing" style="width:100%">
                            <file-upload :disabled="isView" :limit="1" v-model="viewModel.file" bizType="UPLOAD_FILE_OTHERS" :bizId="id" :otherList="otherList" @change="(fileList)=>fileChange(fileList)"> </file-upload>
                        </el-form-item>
                    </el-col>

                </el-row>
            </el-card>
        </el-form>
        <div class="submit-footer">
            <el-button icon="el-icon-close" size="small" @click="closeTab" class="drawer-close">{{$t('public.close')}}</el-button>
            <el-button type="primary" v-if="!isView" @click="submitAddForm" :loading="loading" icon="el-icon-check" size="small">{{ $t('inspectionManagement.saveStorage') }}</el-button>
            <!--            <el-button type="primary" v-if="!isView" @click="submitBatchAdd" :loading="loading" icon="el-icon-finished" size="small">{{id == '0'?'批量新增':'批量修改'}}</el-button>-->
        </div>
        <template-dialog :visible.sync="templateVisible" @callback="(row)=>templateDataCallback(row)" />
    </div>

</template>

<script>
import {getType, refreshCache,} from '@/api/basic/dict/type'
import {listAllFactory} from '@/api/basic/factory'
import {listProject} from '@/api/basic/project'
import {listCheckoutUnit} from '@/api/basic/checkoutUnit'
import {listMaterialType} from '@/api/basic/materialtype'

import {
  addInspectionPlan,
  addPlanBatch,
  editPlan,
  editPlanBatch,
  getPlanById,
  getPlanFile,
  getSamplingPlan,
  getVersion,
} from '@/api/inspectionManagement/inspectionManagement'
import {geFileByBiz} from '@/api/file/file'

import FileUploadInput from '@/components/FileUploadInput'
import SupplierDialog from '@/views/components/SupplierDialog'
import MaterialDialog from '@/views/components/MaterialDialog'
import TemplateDialog from '@/views/components/TemplateDialog'
import MeasuringToolDialog from '@/views/components/MeasuringToolDialog'
import InspectionItemInfoVirtual from '@/views/components/InspectionItemInfoVirtual'
import DivisionDialog from '@/views/components/DivisionDialog'
import {samplingPlanlistAPI} from '@/api/basic/transferRule'
export default {
    name: 'editInspectionPlan',
    dicts: ['sys_normal_disable', 'NYIQC_INSPECTIONPLAN_CLASSIFY'],
    components: {
        FileUploadInput,
        SupplierDialog,
        MaterialDialog,
        TemplateDialog,
        MeasuringToolDialog,
        InspectionItemInfoVirtual,
        DivisionDialog,
    },
    data() {
        var validateNumber = (rule, value, callback) => {
                if ((/^[1-9]\d*$/).test(value)) {
                    callback()
                } else {
                    callback(new Error('请输入正整数'))
                }
        }
        return {
            direction: 'rtl',
            disabledMaturity: false,
            addInspectionExemption: false,
            checkFile: [],
            checkFileList: [],
            templateVisible: false,
            drawer: false,
            approvalOpen: false,
            submitType: 'one',
            viewInspectionExemption: false,
            projectList: [],
            inspectionOptions: [
                {
                    value: '1',
                    label: '检验项1',
                },
                {
                    value: '2',
                    label: '检验项2',
                },
            ],
            inspectionTypeUnitOptions: [
                {
                    value: '1',
                    label: '单位1',
                },
                {
                    value: '2',
                    label: '单位2',
                },
            ],
            frequencyOptions: [
                {
                    value: '批',
                    label: '批',
                },
                {
                    value: '件',
                    label: '件',
                },
                {
                    value: '年',
                    label: '年',
                },
                {
                    value: '季',
                    label: '季',
                },
                {
                    value: '月',
                    label: '月',
                },
                {
                    value: '日',
                    label: '日',
                },
            ],
            samplingSchemeOptions: [
                {
                    value: 'GB/T2828.1-2012',
                    label: 'GB/T2828.1-2012',
                },
                {
                    value: '百分比',
                    label: '百分比',
                },
                {
                    value: '固定抽样',
                    label: '固定抽样',
                },
                {
                    value: 'C=0',
                    label: 'C=0',
                },
            ],
            testMethodOptions: [
                {
                    value: '目测',
                    label: '目测',
                },
                {
                    value: '量具',
                    label: '量具',
                },
                {
                    value: '验证',
                    label: '验证',
                },
                {
                    value: 'ny-iqc作业指导书',
                    label: 'ny-iqc作业指导书',
                },
                {
                    value: '核对COA',
                    label: '核对COA',
                },
            ],
            samplingLevelOptions: [
                {
                    value: 'S-1',
                    label: 'S-1',
                },
                {
                    value: 'S-2',
                    label: 'S-2',
                },
                {
                    value: 'S-3',
                    label: 'S-3',
                },
                {
                    value: 'S-4',
                    label: 'S-4',
                },
                {
                    value: 'Ⅰ',
                    label: 'Ⅰ',
                },
                {
                    value: 'Ⅱ',
                    label: 'Ⅱ',
                },
                {
                    value: 'Ⅲ',
                    label: 'Ⅲ',
                },
            ],
            samplingMethodCOptions: [
                {
                    value: '0.01',
                    label: '0.01',
                },
                {
                    value: '0.015',
                    label: '0.015',
                },
                {
                    value: '0.025',
                    label: '0.025',
                },
                {
                    value: '0.04',
                    label: '0.04',
                },
                {
                    value: '0.1',
                    label: '0.1',
                },
                {
                    value: '0.15',
                    label: '0.15',
                },
                {
                    value: '0.25',
                    label: '0.25',
                },
                {
                    value: '0.4',
                    label: '0.4',
                },
                {
                    value: '0.65',
                    label: '0.65',
                },
                {
                    value: '1',
                    label: '1',
                },
                {
                    value: '1.5',
                    label: '1.5',
                },
                {
                    value: '4',
                    label: '4',
                },
                {
                    value: '6.5',
                    label: '6.5',
                },
                {
                    value: '10',
                    label: '10',
                },
            ],
            samplingLevelTypeOptions: [
                {
                    value: '正常',
                    label: '正常',
                },
                {
                    value: '放宽',
                    label: '放宽',
                },
                {
                    value: '加严',
                    label: '加严',
                },
            ],
            samplingFixedTypeOptions: [
                {
                    value: '批',
                    label: '批',
                },
                {
                    value: '件',
                    label: '件',
                },
            ],
            specialCharacteristicsOptions: [
                {
                    value: '空',
                    label: '空',
                },
                {
                    value: '○',
                    label: '○',
                },
                {
                    value: '◆',
                    label: '◆',
                },
                {
                    value: '★',
                    label: '★',
                },
            ],
            addModel: {},
            formMaterial: false,
            viewModel: {
                planFrequency: '批',
                materialMin: null,
                frequencyValue: 1,
                file: null,
                version: null,
                inspectionExemptionPlan: '1',
                uploadAttachments: null,
                supplierName: null,
                materialName: null,
                supplierType: null,
                factoryName: [],
                divisionName: '', // 事业部
                baseName: '', //  基地
                workshop: '', // 车间
                // entryName:'',//项目名称
                documentNo:'',//文件编号
                divisionId:'',//事业部id
            },
            editModel: {},
            approvalForm: {
                status: '1',
                textarea: '',
            },
            selBtn: 1,
            id: this.$route.params.id,
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 字典表格数据
            typeList: [
                {
                    samplingOne: null,
                    samplingTwo: null,
                    samplingThree: null,
                    measuringTool: null,
                    inspectionType: '1',
                    specialCharacteristics: '0',
                    projectCode: null,
                },
            ],
            isView: this.$route.query.isView ? true : false,
            factoryList: [],
            maturityList: [
                {
                    label: '1',
                    value: '1',
                },
                {
                    label: '2',
                    value: '2',
                },
                {
                    label: '3',
                    value: '3',
                },
                {
                    label: '4',
                    value: '4',
                },
                {
                    label: '5',
                    value: '5',
                },
                {
                    label: '6',
                    value: '6',
                },
                {
                    label: '7',
                    value: '7',
                },
            ],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            unitList: [],
            picFile: [],
            drawingList: [],
            otherList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                noticeTitle: undefined,
                noticeType: undefined,
                hasRead: undefined,
                createTime: undefined,
            },
            // 表单参数
            form: {},
            images: [],
            otherFileList: [],
            samplingPlanList: [],
            // 表单校验
            rules: {
                // supplierType: [
                //     {
                //         required: true,
                //         message: '供应商类别不能为空',
                //         trigger: 'change',
                //     },
                // ],
                divisionName: [
                    {  required: true,  message: this.$t('formValidation.businessUnitCannotBeEmpty'),  trigger: 'change' },
                ],
                materialName: [
                    {
                        required: true,
                        message: this.$t('formValidation.materialNameCannotBeEmpty'),
                        trigger: 'change',
                    },
                ],
                materialType: [
                    {
                        required: true,
                        message: '物料类型不能为空',
                        trigger: 'change',
                    },
                ],
                materialCode: [
                    {
                        required: true,
                        message: this.$t('formValidation.materialCodeCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
                factoryName: [
                    {
                        required: true,
                        message: this.$t('formValidation.factoryAreaCannotBeEmpty'),
                        trigger: 'change',
                    },
                ],
                planFrequency: [
                    {
                        required: true,
                        message: '频率不能为空',
                        trigger: 'change',
                    },
                ],
                frequencyValue: [
                    {
                        required: true,
                        message: '频率值不能为空',
                        trigger: 'blur',
                    },{ validator: validateNumber, trigger: 'blur' }
                ],
                version: [
                    {
                        required: true,
                        message: this.$t('formValidation.versionNumberCannotBeEmpty'),
                        trigger: 'change',
                    },
                ],
                maturity: [
                    {
                        required: true,
                        message: '成熟度不能为空',
                        trigger: 'change',
                    },
                ],
            },
            fullscreen: false,
            isAdd:null,
            inpectItemData: [],
            samplinglist:[],
            currentSamplinglist:[]
        }
    },
    created() {
        this.getFactoryList()
        // this.getProjectList()
        this.getUnitList()
        // this.getSamplingPlan()
        if (this.id != '0') {
            this.getPlanById()
        } else {
            this.inpectItemData = []
        }
        this.sPlanlist()
    },
    methods: {
        changeSamplinglist(){
            this.currentSamplinglist = JSON.parse(JSON.stringify(this.samplinglist))
            if(this.viewModel.divisionName){
               this.currentSamplinglist = this.currentSamplinglist.filter(val => val.divisionName == this.viewModel.divisionName) 
            }
            console.log(this.viewModel,this.currentSamplinglist)
        },
        sPlanlist() {
            var data= {
                pageNum: 1,
                pageSize: 1000,
            }
            samplingPlanlistAPI(data).then((res) => {
                this.samplinglist=res.data
                this.changeSamplinglist()
            })
        },
        materialTypeRemoteMethod(val, cb) {
            listMaterialType({ typeName: val }).then((res) => {
                cb(res.rows)
            })
        },
        handleMaterialTypeSelect(e, scope) {
            // this.dialogForm.materialType = e
            this.viewModel.materialType = e.typeName
            this.$forceUpdate()
        },
        changeSampling(e, scope) {
            console.log(scope.$index)
            this.typeList[scope.$index].samplingTwo = null
            this.typeList[scope.$index].samplingThree = null
        },
        getPlanById() {
            // let split = this.id.split(",");
            this.loading=true
            const loading = this.$loading({  lock: true, text: 'Loading', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)' });
            getPlanById(this.id).then((res) => {
                this.viewModel = res.data
                let factoryName = []
                res.data.factoryList.forEach((io) => {
                    factoryName.push(io.planFactoryName)
                })
                this.viewModel.factoryName = factoryName
                let checkItemList = [...res.data.checkItemList]
                checkItemList.forEach((io) => {
                    io.targetValue = this.formatTargetValueTo(io.targetValue)
                })
                this.inpectItemData = res.data.checkItemList
                this.isAdd = res.data.isAdd
                // this.getPlanFile(res.data)
                this.geFileByBiz(this.id)
                res.data.drawingsBizId &&
                    this.getDrawingFile(res.data.drawingsBizId)
                res.data.checkBizId && this.getCheckFile(res.data.checkBizId)
                res.data.elseBizId && this.getOtherFile(res.data.elseBizId)
                this.loading=false
                loading.close();
            })
        },
        formatTargetValueTo(targetValue) {
            if (
                Object.prototype.toString.call(targetValue) !==
                '[object String]'
            ) {
                return ''
            }
            return targetValue.replace(/&lt;|&gt;|&amp;/g, function (match) {
                return {
                    '&lt;': '<',
                    '&gt;': '>',
                    '&amp;': '&',
                }[match]
            })
        },
        formatTargetValueForward(targetValue) {
            if (
                Object.prototype.toString.call(targetValue) !==
                '[object String]'
            ) {
                return ''
            }
            return targetValue.replace(/<|>|&/g, function (match) {
                return {
                    '<': '&lt;',
                    '>': '&gt;',
                    '&': '&amp;',
                }[match]
            })
        },
        geFileByBiz(id) {
            geFileByBiz({ bizId: id }).then((res) => {
                let drawingList = []
                let otherList = []
                let checkFile = []
                res.data.forEach((io) => {
                    if (io.bizType === 'UPLOAD_FILE') {
                        drawingList.push(io)
                    }
                    if (io.bizType === 'UPLOAD_FILE_OTHERS') {
                        otherList.push(io)
                    }
                    if (io.bizType === 'UPLOAD_FILE_CHECK') {
                        checkFile.push(io)
                    }
                })
                console.log('otherListotherList====>', otherList)
                this.picFile = drawingList
                this.checkFile = checkFile
                this.images = drawingList
                this.otherList = otherList
                this.otherFileList = otherList
                this.checkFileList = checkFile
            })
        },
        getSamplingPlan() {
            getSamplingPlan().then((res) => {
                this.samplingPlanList = res.rows
            })
        },
        changeProject(e) {
            let obj = this.projectList.find((item) => {
                return item.projectName === e.row.projectName
            })
            this.typeList[e.$index].projectCode = obj.projectCode
            this.typeList[e.$index].projectId = obj.projectId
        },
        getProjectList() {
            listProject().then((res) => {
                this.projectList = res.rows
            })
        },
        getUnitList() {
            listCheckoutUnit().then((res) => {
                this.unitList = res.rows
            })
        },
        fileChange(fileList) {
            this.otherFileList = fileList
        },
        picChange(fileList) {
            console.log('picChange===>', fileList)
            this.images = fileList
        },
        checkChange(fileList) {
            this.checkFileList = fileList
        },
        getFactoryList() {
            listAllFactory().then((res) => {
                this.factoryList = res.data.map(item=>{
                    return {
                        ...item,
                        newFactoryName:item.plantName+'-'+item.plantCode
                    }
                })
            })
        },
        // 厂区下拉回显
        factoryVisibleFN(isShow){
            console.log('isShow',isShow)
            if(isShow) return this.viewModel.materialCode || this.$modal.msgError('请先选择物料')
            // this.factoryChange(this.viewModel.factoryName)
        },
        // 厂区选择移除tag
        factoryRemoveFN(removeItems){
            console.log('removeItems:',removeItems)
            console.log(' this.viewModel.factoryList:', this.viewModel.factoryList)
        },
        factoryChange(e) {
            console.log(e)
            let factoryCodes = []
            let factoryList = []
            this.factoryList.forEach((io) => {
                e.forEach((ko) => {
                    if (ko === io.plantName) {
                        factoryList.push({
                            planFactoryName: ko,
                            planFactoryCode: io.plantCode,
                        })
                    }
                })
            })
            // let obj = this.factoryList.find((item) => {
            //     return item.factoryName === e
            // })
            this.viewModel.factoryList = factoryList
            this.currentFactory = factoryList
            this.buildVersion()
        },
        templateDataCallback(rows) {
            this.typeList = rows
        },
        supplierDataCallback(row) {
            this.viewModel.supplierName = row.supplierName
            this.$set(this.viewModel, 'supplierCode', row.supplierCode)
            this.$set(this.viewModel, 'supplierType', row.supplierCategory)
            this.$refs.planForm.validateField('supplierCode')
            this.$refs.planForm.validateField('supplierType')
            this.buildVersion()
        },
        materialDataCallback(row) {
            console.log(row.maturity)
            let maturity = null
            this.formMaterial = false
            if (row.maturity === '1' || row.maturity === '2') {
                maturity = 'ENW'
                this.formMaterial = true
            }
            if (row.maturity === '3' || row.maturity === '6') {
                maturity = 'DWG'
                this.formMaterial = true
            }
            this.$set(this.viewModel, 'materialName', row.materialName)
            this.$set(this.viewModel, 'materialCode', row.materialCode)
            this.$set(this.viewModel, 'materialType', row.materialType)

            // 带出厂区
            this.$set(this.viewModel, 'factoryCode', row.plantCode)
            this.$set(this.viewModel, 'factoryName', [row.plantName])
            this.viewModel.factoryList = [{
                planFactoryName: row.plantName,
                planFactoryCode: row.plantCode,
            }]

            // 带出版本号
            this.$set(this.viewModel, 'version', row.version)

            this.$set(this.viewModel, 'maturity', maturity)
            this.$set(this.viewModel, 'materialMin', row.groupingCode)
            this.$refs.planForm.validateField('materialName')
            this.$refs.planForm.validateField('materialType')
            this.$refs.planForm.validateField('materialCode')
            // this.$refs.planForm.validateField('factoryName')
            // this.$refs.planForm.validateField('factoryCode')
            this.$refs.planForm.validateField('maturity')
            this.$refs.planForm.validateField('materialMin')
            // this.currentFactoryName = row.factoryName
            this.viewModel.materialTypeName = row.materialTypeName
            // this.buildVersion()
            this.getPlanFile(row)
        },
        getPlanFile(row) {
            getPlanFile({
                materialCode: row.materialCode,
                materialMin: row.materialType,
            })
                .then((res) => {
                    this.getDrawingFile(res.data.id)
                    // this.getCheckFile(res.data.checkBizId)
                    // this.getOtherFile(res.data.elseBizId)
                })
                .catch((res) => {})
        },
        getDrawingFile(id) {
            geFileByBiz({ bizId: id }).then((res) => {
                if (res.data && res.data.length > 0) {
                    let drawingList = []
                    let otherList = []
                    let checkFile = []
                    res.data.forEach((io) => {
                        if (io.bizType === 'UPLOAD_FILE') {
                            drawingList.push(io)
                        }
                        if (io.bizType === 'UPLOAD_FILE_OTHERS') {
                            otherList.push(io)
                        }
                        if (io.bizType === 'UPLOAD_FILE_CHECK') {
                            checkFile.push(io)
                        }
                    })
                    console.log('otherListotherList====>', otherList)
                    this.picFile = drawingList
                    this.checkFile = checkFile
                    this.images = drawingList
                    this.otherList = otherList
                    this.otherFileList = otherList
                    this.checkFileList = checkFile
                }
            })
        },
        // getCheckFile(id) {
        //     geFileByBiz({ bizId: id }).then((res) => {
        //         if (res.data && res.data.length > 0) {
        //             this.checkFile = res.data
        //             console.log('this.picFile=======', this.picFile)
        //         }
        //     })
        // },
        // getOtherFile(id) {
        //     geFileByBiz({ bizId: id }).then((res) => {
        //         if (res.data && res.data.length > 0) {
        //             this.otherList = res.data
        //             console.log('this.picFile=======', this.picFile)
        //         }
        //     })
        // },
        buildVersion() {
            if (
                this.viewModel.materialCode && Array.isArray(this.currentFactory) && this.currentFactory.length > 0
            ) {
                getVersion({
                    factoryList: this.currentFactory,
                    materialCode: this.viewModel.materialCode,
                    supplierCode: this.viewModel.supplierCode,
                    id: this.id != '0'? this.id:undefined
                }).then((res) => {
                        if(res.code == 200) return this.viewModel.version = res.msg
                    })
                    .catch((error) => {
                        this.viewModel.version = undefined
                    })
            }else{
                this.$modal.msgError('物料和厂区不能为空！')
            }
        },
        closeTab() {
            this.$router.push({ path: '/inspectionPlan' })
        },
        effectDateChange(e, scope) {
            if (parseInt(e) > 0) {
                this.typeList[scope.$index].endDate = this.getNewDay(
                    scope.row.approvalTime,
                    e
                )
            }
        },
        getNewDay(dateTemp, days) {
            var dateTemp = dateTemp.split('-')
            //转换为MM-DD-YYYY格式
            var nDate = new Date(
                dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]
            )
            var millSeconds = Math.abs(nDate) + days * 24 * 60 * 60 * 1000
            var rDate = new Date(millSeconds)
            var year = rDate.getFullYear()
            var month = rDate.getMonth() + 1
            if (month < 10) month = '0' + month
            var date = rDate.getDate()
            if (date < 10) date = '0' + date
            return year + '-' + month + '-' + date
        },
        drawerClose() {
            this.drawer = false
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                dictId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.typeList.push({
                samplingOne: null,
                samplingTwo: null,
                samplingThree: null,
                measuringTool: null,
                inspectionType: '1',
                specialCharacteristics: '0',
                projectCode: null,
            })
        },
        handleSelectTemplate() {
            this.templateVisible = true
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.dictId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const dictId = row.dictId || this.ids
            getType(dictId).then((response) => {
                this.form = response.data
                this.open = true
                this.title = '修改字典类型'
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            let isTrue = false
            this.$refs['planForm'].validate((valid) => {
                if (valid) {
                    isTrue = true
                } else {
                    this.$modal.msgError(this.$t('formValidation.theBasicInformationIsIncomplete'))
                    isTrue = false
                }
            })
            return isTrue
        },

        /** 发起检验提交 */
        submitAddForm: function () {
            this.submitType = 'one'
            if (this.submitForm()) {
                this.$refs.inspectSubmit.submitAddForm()
            }
        },
        submitBatchAdd: function () {
            this.submitType = 'batch'
            if (this.submitForm()) {
                this.$refs.inspectSubmit.submitAddForm()
            }
        },
        submitCallback(params,isAdd) {
            this.loading = true
            let fileId = []
            if (this.otherFileList.length) {
                this.otherFileList.forEach((io) => {
                    fileId.push(io.id)
                })
            }
            if (this.checkFileList.length) {
                this.checkFileList.forEach((io) => {
                    fileId.push(io.id)
                })
            }

            if (this.images.length) {
                this.images.forEach((io) => {
                    fileId.push((io.response && io.response.data.id) || io.id)
                })
            }
            let formatData = [...params]
            // formatData.forEach((io) => {
            //     io.targetValue = this.formatTargetValueForward(io.targetValue)
            // })
            let submitData = {
                ...this.viewModel,
                isAdd,
                checkItemList: formatData,
                fileId: fileId.join(','),
            }
            delete submitData.factoryName
            console.log(submitData)
            this.submitType === 'one' && this.submitOne(submitData)
            this.submitType === 'batch' && this.submitMore(submitData)
        },
        submitOne(submitData) {
            let action = this.id == '0' ? addInspectionPlan : editPlan
            action(submitData)
                .then((res) => {
                    if (res.code == 200) {
                        this.$modal.msgSuccess('操作成功!')
                        this.$router.go(-1)
                    } else {
                        this.$modal.msgError(res.msg)
                        this.loading = false
                    }
                })
                .catch((error) => {
                    this.loading = false
                })
        },
        submitMore(submitData) {
            let action = this.id == '0' ? addPlanBatch : editPlanBatch
            action(submitData)
                .then((res) => {
                    if (res.code == 200) {
                        this.$modal.msgSuccess('操作成功!')
                        this.$router.go(-1)
                    } else {
                        this.$modal.msgError(res.msg)
                        this.loading = false
                    }
                })
                .catch((error) => {
                    this.loading = false
                })
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            if (this.typeList.length === 1) {
                this.$modal.msgWarning('请至少保留一条检验项!')
                return
            }
            this.typeList.splice(row.$index, 1)
        },
        /** 查看按钮操作 */
        handleView(row) {
            this.form = row
            this.viewInspectionExemption = true
            //   if(row.hasRead == 0){
            //     readNotice(row.noticeId).then(res=>{
            //       if(res.code == 200){
            //         this.handleQuery()
            //       }
            //     })
            //   }
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.drawer = true
        },
        /** 关闭抽屉操作 */
        handleClose(row) {
            this.drawer = false
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'system/dict/type/export',
                {
                    ...this.queryParams,
                },
                `type_${new Date().getTime()}.xlsx`
            )
        },
        /** 刷新缓存按钮操作 */
        handleRefreshCache() {
            refreshCache().then(() => {
                this.$modal.msgSuccess('刷新成功')
            })
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep .el-card {
    padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    float: left;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    line-height: 40px;
    display: flex;
    justify-content: center;
}
.header-right {
    float: right;
}
.container-header {
    float: left;
    width: 100%;
    border-bottom: 1px solid #ededf2;
    padding-left: 12px;
}
.container-table {
    float: left;
    margin-top: 6px;
    width: 100%;
    // max-height: calc(100vh - 600px);
    overflow: auto;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.hign-line {
    position: relative;
    left: -8px;
    top: 14px;
    height: 12px;
    border-radius: 2px;
    border: 1px solid #0b7be3;
    float: left;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}
.submit-footer {
    height: 52px;
    background: #ffffff;
    box-shadow: 0px -5px 5px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px 4px 0px 0px;
    position: fixed;
    z-index: 9;
    bottom: 0px;
    width: 100%;
    left: 0px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.samplingPercent {
    position: absolute;
    z-index: 9;
    right: 20px;
}
::v-deep .el-card {
    padding-top: 0px;
}
.app-detail {
    max-height: calc(100vh - 180px);
    overflow: auto;
}

::v-deep .el-form-item {
    margin-bottom: 3px !important;
}
</style>
